package com.example.gulimall.seckill.controller;

import com.example.common.to.kill.SecKillRedisTo;
import com.example.common.utils.R;
import com.example.gulimall.seckill.service.SecKillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/sec/kill")
public class SecKillController {

    @Autowired private SecKillService secKillService;

    /**
     * 获取当前时间可以参加的所有商品信息
     */
    @ResponseBody
    @GetMapping("/current")
    public R getCurrentSecKillSku () {
        List<SecKillRedisTo> tos = this.secKillService.getCurrentSecKillSku();
        return R.ok().put("data", tos);
    }

    @ResponseBody
    @GetMapping("/skuInfo/{skuId}")
    public R getSkuInfo (@PathVariable("skuId") Long skuId){
        return R.ok().put("data", this.secKillService.getSkuInfo (skuId));
    }

    /**
     * 秒杀功能：流程
     *
     * 1. 判断登录
     * 2. 校验参数的合法性
     * 3. 获取分布式信号量进行扣减
     * 4. 快速创建秒杀单，用户，订单号，商品  （发送MQ）
     * 5. 收货地址填写，
     * 6. 确认支付
     */
    @GetMapping("/kill")
    public String secKill (@RequestParam("killId") String killId,
                      @RequestParam("key") String key,
                      @RequestParam("num") Integer num, Model model
                      ) {
        String orderSn = this.secKillService.secKill(killId, key, num);
        model.addAttribute("orderSn", orderSn);
        return "success";
    }
}
